package com.example.service.impl;

import com.example.mapper.StudentMapper;
import com.example.pojo.Student;
import com.example.service.StudentLogService;
import com.example.service.StudentService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.pojo.PageBean;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private StudentLogService studentLogService;
    @Override
    public PageBean list(Integer page, Integer pageSize,String name,Integer gender) {
        //pageHelper插件
        PageHelper.startPage(page,pageSize);                                     //设置分页查询参数
        List<Student> list = studentMapper.list(name,gender);                    //执行查询，该插件pagehelper会自动对代码进行修改2次
        Page<Student> studentPage  = (Page) list;
        PageBean studentPageBean = new PageBean(studentPage.getTotal(),studentPage.getResult());
        return studentPageBean;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void deleteById(Integer id) {

        try {
            studentMapper.deleteById(id);
        }finally {
            /**
             * 记录删除学生日志
             * 对应数据库库的 stu_delete_log表
             * 无论删除成功与否都要添加日志，所以记录日志不一定代表删除成功
             */
            studentLogService.studentDeleteLog(id);
        }
    }

    @Override
    public void add(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.add(student);
    }

    @Override
    public void update(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }
}
